package world.snowcrystal.openapi.controller;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import world.snowcrystal.client.SnowCrystalApiClient;
import world.snowcrystal.commons.exception.BusinessException;
import world.snowcrystal.commons.model.dto.BaseResponse;
import world.snowcrystal.commons.model.dto.DeleteRequest;
import world.snowcrystal.commons.model.dto.PrimaryKeyRequest;
import world.snowcrystal.commons.model.dto.interfaceinfo.InterfaceInfoAddRequest;
import world.snowcrystal.commons.model.dto.interfaceinfo.InterfaceInfoInvokeRequest;
import world.snowcrystal.commons.model.dto.interfaceinfo.InterfaceInfoQueryRequest;
import world.snowcrystal.commons.model.dto.interfaceinfo.InterfaceInfoUpdateRequest;
import world.snowcrystal.commons.model.entity.InterfaceInfo;
import world.snowcrystal.commons.model.entity.User;
import world.snowcrystal.commons.model.enums.ApplicationResponseStatusCode;
import world.snowcrystal.commons.model.enums.InterfaceStatusEnum;
import world.snowcrystal.commons.model.enums.SortOrderEnum;
import world.snowcrystal.commons.model.enums.UserRoleEnum;
import world.snowcrystal.commons.service.InterfaceInfoService;
import world.snowcrystal.commons.service.UserService;
import world.snowcrystal.openapi.annotation.AuthorityCheck;
import world.snowcrystal.openapi.utils.ResultUtils;

import java.util.List;

/**
 * 接口管理
 */
@RestController
@RequestMapping("/interfaceInfo")
@Slf4j
public class InterfaceInfoController {

    @Resource
    private InterfaceInfoService interfaceInfoService;

    @Resource
    private UserService userService;


    // region 增删改查

    /**
     * 创建
     *
     * @param interfaceInfoAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addInterfaceInfo(@RequestBody InterfaceInfoAddRequest interfaceInfoAddRequest, HttpServletRequest request) {
        if (interfaceInfoAddRequest == null) {
            throw new BusinessException(ApplicationResponseStatusCode.PARAMS_ERROR);
        }
        InterfaceInfo interfaceInfo = new InterfaceInfo();
        BeanUtils.copyProperties(interfaceInfoAddRequest, interfaceInfo);
        // 校验
        User loginUser = userService.getLoginUser(request);
        interfaceInfo.setUserId(loginUser.getId());
        interfaceInfoService.validInterfaceInfo(interfaceInfo, true);
        boolean result = interfaceInfoService.save(interfaceInfo);
        if (!result) {
            throw new BusinessException(ApplicationResponseStatusCode.OPERATION_ERROR);
        }
        long newInterfaceInfoId = interfaceInfo.getId();
        return ResultUtils.success(newInterfaceInfoId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteInterfaceInfo(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ApplicationResponseStatusCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        InterfaceInfo oldInterfaceInfo = interfaceInfoService.getById(id);
        if (oldInterfaceInfo == null) {
            throw new BusinessException(ApplicationResponseStatusCode.NOT_FOUND_ERROR);
        }
        // 仅本人或管理员可删除
        if (!oldInterfaceInfo.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ApplicationResponseStatusCode.NO_AUTH_ERROR);
        }
        boolean b = interfaceInfoService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新
     *
     * @param interfaceInfoUpdateRequest
     * @param request
     * @return
     */
    @PostMapping("/update")
    public BaseResponse<Boolean> updateInterfaceInfo(@RequestBody InterfaceInfoUpdateRequest interfaceInfoUpdateRequest,
                                                     HttpServletRequest request) {
        if (interfaceInfoUpdateRequest == null || interfaceInfoUpdateRequest.getId() <= 0) {
            throw new BusinessException(ApplicationResponseStatusCode.PARAMS_ERROR);
        }
        InterfaceInfo interfaceInfo = new InterfaceInfo();
        BeanUtils.copyProperties(interfaceInfoUpdateRequest, interfaceInfo);
        User user = userService.getLoginUser(request);
        interfaceInfo.setUserId(user.getId());
        // 参数校验
        interfaceInfoService.validInterfaceInfo(interfaceInfo, false);
        long id = interfaceInfoUpdateRequest.getId();
        // 判断是否存在
        InterfaceInfo oldInterfaceInfo = interfaceInfoService.getById(id);
        if (oldInterfaceInfo == null) {
            throw new BusinessException(ApplicationResponseStatusCode.NOT_FOUND_ERROR);
        }
        // 仅本人或管理员可修改
        if (!oldInterfaceInfo.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ApplicationResponseStatusCode.NO_AUTH_ERROR);
        }
        boolean result = interfaceInfoService.updateById(interfaceInfo);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     */
    @GetMapping("/get")
    public BaseResponse<InterfaceInfo> getInterfaceInfoById(Long id) {
        if (id <= 0) {
            throw new BusinessException(ApplicationResponseStatusCode.PARAMS_ERROR);
        }
        InterfaceInfo interfaceInfo = interfaceInfoService.getById(id);
        return ResultUtils.success(interfaceInfo);
    }

    /**
     * 获取列表（仅管理员可使用）
     *
     * @param interfaceInfoQueryRequest
     * @return
     */
    @AuthorityCheck(value = UserRoleEnum.ADMIN)
    @GetMapping("/list")
    public BaseResponse<List<InterfaceInfo>> listInterfaceInfo(InterfaceInfoQueryRequest interfaceInfoQueryRequest) {
        InterfaceInfo interfaceInfoQuery = new InterfaceInfo();
        if (interfaceInfoQueryRequest != null) {
            BeanUtils.copyProperties(interfaceInfoQueryRequest, interfaceInfoQuery);
        }
        QueryWrapper<InterfaceInfo> queryWrapper = new QueryWrapper<>(interfaceInfoQuery);
        List<InterfaceInfo> interfaceInfoList = interfaceInfoService.list(queryWrapper);
        return ResultUtils.success(interfaceInfoList);
    }

    /**
     * 分页获取列表
     *
     * @param interfaceInfoQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page")
    public BaseResponse<Page<InterfaceInfo>>
    listInterfaceInfoByPage(@RequestBody InterfaceInfoQueryRequest interfaceInfoQueryRequest,
                            HttpServletRequest request) {

        log.debug("listInterfaceInfoByPage, request:{}", JSONUtil.toJsonStr(interfaceInfoQueryRequest));
        if (interfaceInfoQueryRequest == null) {
            throw new BusinessException(ApplicationResponseStatusCode.PARAMS_ERROR);
        }
        InterfaceInfo interfaceInfoQuery = new InterfaceInfo();
        BeanUtils.copyProperties(interfaceInfoQueryRequest, interfaceInfoQuery);
        Long current = interfaceInfoQueryRequest.getCurrent();
        Long size = interfaceInfoQueryRequest.getPageSize();
        String sortField = interfaceInfoQueryRequest.getSortField();
        String sortOrder = interfaceInfoQueryRequest.getSortOrder();
        String description = interfaceInfoQuery.getDescription();
        // description 需支持模糊搜索
        interfaceInfoQuery.setDescription(null);
        // 限制爬虫
        if (size > 50) {
            throw new BusinessException(ApplicationResponseStatusCode.PARAMS_ERROR);
        }
        QueryWrapper<InterfaceInfo> queryWrapper = new QueryWrapper<>(interfaceInfoQuery);
        queryWrapper.like(StringUtils.isNotBlank(description), "description", description);
        queryWrapper.orderBy(StringUtils.isNotBlank(sortField),
                SortOrderEnum.ASCENDING.getValue().equals(sortOrder), sortField);
        Page<InterfaceInfo> interfaceInfoPage = interfaceInfoService.page(new Page<>(current, size), queryWrapper);
        return ResultUtils.success(interfaceInfoPage);
    }

    // endregion


    @PostMapping("/online")
    @AuthorityCheck(value = UserRoleEnum.ADMIN)
    public BaseResponse<Boolean> onlineInterface(
            @RequestBody PrimaryKeyRequest primaryKeyRequest) {

        Long id = primaryKeyRequest.getId();
        if (primaryKeyRequest == null || id == null) {
            throw new BusinessException(ApplicationResponseStatusCode.PARAMS_ERROR);
        }
        InterfaceInfo interfaceInfo = interfaceInfoService.getById(id);
        if (interfaceInfo == null) {
            throw new BusinessException(ApplicationResponseStatusCode.NOT_FOUND_ERROR);
        }

        //
        InterfaceInfo inf = new InterfaceInfo();
        inf.setId(id);
        inf.setStatus(InterfaceStatusEnum.ONLINE.getValue());
        final boolean result = interfaceInfoService.updateById(inf);
        return ResultUtils.success(result);
    }

    @PostMapping("/offline")
    @AuthorityCheck(value = UserRoleEnum.ADMIN)
    public BaseResponse<Boolean> offlineInterface(
            @RequestBody PrimaryKeyRequest primaryKeyRequest) {

        Long id = primaryKeyRequest == null ? null : primaryKeyRequest.getId();
        if (primaryKeyRequest == null || id == null) {
            throw new BusinessException(ApplicationResponseStatusCode.PARAMS_ERROR);
        }
        InterfaceInfo interfaceInfo = interfaceInfoService.getById(id);
        if (interfaceInfo == null) {
            throw new BusinessException(ApplicationResponseStatusCode.NOT_FOUND_ERROR);
        }
        //
        InterfaceInfo inf = new InterfaceInfo();
        inf.setId(id).setStatus(InterfaceStatusEnum.OFFLINE.getValue());
        final boolean result = interfaceInfoService.updateById(inf);
        return ResultUtils.success(result);
    }

    @PostMapping("/invoke")
    public BaseResponse<String> invokeInterface(@RequestBody InterfaceInfoInvokeRequest invokeRequest,
                                                HttpServletRequest request) {
        log.info("interface invoke request: {}", invokeRequest.getId());
        log.info("params : {}", invokeRequest.getUserRequestParams());
        // 检查参数是否为空
        if (invokeRequest == null || invokeRequest.getId() == null) {
            throw new BusinessException(ApplicationResponseStatusCode.PARAMS_ERROR);
        }
        // 检查是否存在此接口并且状态正常
        InterfaceInfo interfaceInfo = interfaceInfoService.getById(invokeRequest.getId());
        if (interfaceInfo == null || InterfaceStatusEnum.ONLINE.getValue() != interfaceInfo.getStatus()) {
            throw new BusinessException(ApplicationResponseStatusCode.NOT_FOUND_ERROR);
        }

        world.snowcrystal.model.entity.User user = JSONUtil.toBean(invokeRequest.getUserRequestParams(), world.snowcrystal.model.entity.User.class);
        final User loginUser = userService.getLoginUser(request);
        final String accessKey = loginUser.getAccessKey();
        final String secretKey = loginUser.getSecretKey();
        log.info("loginUser : {}", loginUser.getUserAccount());
        // 尝试调用
        String result;
        try {
            SnowCrystalApiClient client = new SnowCrystalApiClient(new RestTemplate(), accessKey, secretKey);
            result = client.invoke("http://localhost:8080/api/name/", user);
        } catch (Exception e) {
            throw new BusinessException(ApplicationResponseStatusCode.SYSTEM_ERROR, e.getMessage());
        }
        // 返回调用结果
        return ResultUtils.success(result);
    }
}
